<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="时间维度">
                    <el-select v-model="searchForm.timeDimension" placeholder="请选择时间维度" clearable style="width: 200px;">
                        <el-option label="日" :value="1" />
                        <el-option label="月" :value="2" />
                        <el-option label="年" :value="3" />
                    </el-select>
                </el-form-item>

                <el-form-item label="时间范围">
                    <el-date-picker v-if="searchForm.timeDimension === 1" v-model="searchForm.time" type="date"
                        placeholder="选择日期" value-format="YYYY-MM-DD" />
                    <el-date-picker v-if="searchForm.timeDimension === 2" v-model="searchForm.time" type="month"
                        placeholder="选择月份" value-format="YYYY-MM" />
                    <el-date-picker v-if="searchForm.timeDimension === 3" v-model="searchForm.time" type="year"
                        placeholder="选择年份" value-format="YYYY" />
                </el-form-item>

                <el-form-item label="段选择">
                    <el-select v-model="searchForm.segmentIds" placeholder="请选择段" clearable multiple  style="width: 300px;">
                        <el-option v-for="segment in segmentList" :key="segment.id" :label="segment.name"
                            :value="segment.id" />
                    </el-select>
                </el-form-item>
<!-- 
                <el-form-item>
                    <el-checkbox v-model="searchForm.onlyAbnormal">仅显示异常</el-checkbox>
                </el-form-item> -->

                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                    <el-button @click="handleExport">导出数据</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 图表区域 -->
        <div class="chart-area">
            <el-row :gutter="20">
                <!-- 压力衰减趋势图 -->
                <el-col :span="12">
                    <el-card class="chart-card">
                        <Echarts :option="trendChartOption" :style="{ height: '400px' }" ref="trendChartRef" />
                    </el-card>
                </el-col>

                <!-- 监测点关系图 -->
                <el-col :span="12">
                    <el-card class="chart-card">
                        <Echarts :option="relationChartOption" :style="{ height: '400px' }" ref="relationChartRef" />
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!-- 压降表格 -->
        <el-card class="table-card">
            <template #header>
                <div class="table-header">
                    <span>压降数据表格</span>
                </div>
            </template>
            <el-table :data="pressureTableData" border stripe v-loading="tableLoading">
                <el-table-column prop="segmentName" label="段名称" align="center" />
                <el-table-column prop="upstreamCode" label="上游编码" align="center" />
                <el-table-column prop="downstreamCode" label="下游编码" align="center" />
                <el-table-column label="理论压降(MPa)" align="center">
                    <template #default="{ row }">
                        {{ row.thDropMpa?.toFixed(3) || '-' }}
                    </template>
                </el-table-column>
                <el-table-column label="实际压降(MPa)" align="center">
                    <template #default="{ row }">
                        {{ row.actDropMpa?.toFixed(3) || '-' }}
                    </template>
                </el-table-column>
                <el-table-column label="偏差(MPa)" align="center">
                    <template #default="{ row }">
                        <span :class="getDeltaClass(row.deltaMpa)">
                            {{ row.deltaMpa?.toFixed(3) || '-' }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="相对偏差" align="center">
                    <template #default="{ row }">
                        <span :class="getDeltaClass(row.deltaRatio)">
                            {{ row.deltaRatio ? (row.deltaRatio * 100).toFixed(1) + '%' : '-' }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="是否异常" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.isAbnormal ? 'danger' : 'success'">
                            {{ row.isAbnormal ? '异常' : '正常' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="上游样本数" align="center">
                    <template #default="{ row }">
                        {{ row.sampleCntUp || 0 }}
                    </template>
                </el-table-column>
                <el-table-column label="下游样本数" align="center">
                    <template #default="{ row }">
                        {{ row.sampleCntDn || 0 }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="120">
                    <template #default="{ row }">
                        <el-button type="text" @click="viewSegmentDetail(row)">详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 异常提示区域 -->
        <el-card class="abnormal-tips-card" v-if="abnormalTips.length > 0">
            <template #header>
                <div class="tips-header">
                    <span>异常压力点提示</span>
                </div>
            </template>
            <div class="tips-content">
                <div v-for="tip in abnormalTips" :key="tip.segmentId" class="tip-item">
                    <div class="tip-title">
                        <el-tag type="danger" size="small">异常</el-tag>
                        {{ tip.segmentName }}
                    </div>
                    <div class="tip-detail">
                        <span>时间：{{ tip.tsHour }}</span>
                        <span>上游：{{ tip.upstreamCode }}</span>
                        <span>下游：{{ tip.downstreamCode }}</span>
                        <span>实际压降：{{ tip.actDropMpa }} MPa</span>
                        <span>理论压降：{{ tip.theoryDropMpa }} MPa</span>
                        <span>偏差：{{ tip.deltaMpa }} MPa</span>
                    </div>
                    <div class="tip-message">{{ tip.message }}</div>
                </div>
            </div>
        </el-card>

        <!-- 段详情对话框 -->
        <el-dialog v-model="detailDialog.visible" :title="`段详情 - ${detailData.segmentName}`" width="600px">
            <el-descriptions :column="2" border>
                <el-descriptions-item label="段名称">{{ detailData.segmentName || '-' }}</el-descriptions-item>
                <el-descriptions-item label="上游编码">{{ detailData.upstreamCode || '-' }}</el-descriptions-item>
                <el-descriptions-item label="下游编码">{{ detailData.downstreamCode || '-' }}</el-descriptions-item>
                <el-descriptions-item label="上游标高">{{ detailData.elevUpM || '-' }} m</el-descriptions-item>
                <el-descriptions-item label="下游标高">{{ detailData.elevDownM || '-' }} m</el-descriptions-item>
                <el-descriptions-item label="上游设计压力">{{ detailData.designPUpMpa || '-' }} MPa</el-descriptions-item>
                <el-descriptions-item label="下游设计压力">{{ detailData.designPDnMpa || '-' }} MPa</el-descriptions-item>
                <el-descriptions-item label="理论压降">{{ detailData.thDropMpa?.toFixed(3) || '-' }}
                    MPa</el-descriptions-item>
                <el-descriptions-item label="实际压降">{{ detailData.actDropMpa?.toFixed(3) || '-' }}
                    MPa</el-descriptions-item>
                <el-descriptions-item label="压降偏差">
                    <span :class="getDeltaClass(detailData.deltaMpa)">
                        {{ detailData.deltaMpa?.toFixed(3) || '-' }} MPa
                    </span>
                </el-descriptions-item>
                <el-descriptions-item label="相对偏差">
                    <span :class="getDeltaClass(detailData.deltaRatio)">
                        {{ detailData.deltaRatio ? (detailData.deltaRatio * 100).toFixed(1) + '%' : '-' }}
                    </span>
                </el-descriptions-item>
            </el-descriptions>
            <template #footer>
                <el-button @click="detailDialog.visible = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Echarts from '@/components/ECharts'

import {
    getPressureGraph,
    getSegmentList,
    getPressureTable,
    getAttenuationTrend,
    getAbnormalTips
} from '@/api/dispatch/analyze/pressure_drop_analysis'

const { proxy } = getCurrentInstance()

// 搜索表单数据
const searchForm = reactive({
    timeDimension: 1,
    time: '',
    areaId: '',
    plantId: '',
    segmentIds: [],
    onlyAbnormal: false
})

// 数据列表
const segmentList = ref([])
const abnormalTips = ref([])
const pressureTableData = ref([])
const graphData = ref(null)
const trendData = ref(null)

// 表格参数
const tableParams = reactive({
    pageNum: 1,
    pageSize: 10
})
const tableTotal = ref(0)
const tableLoading = ref(false)

// 详情对话框
const detailDialog = reactive({
    visible: false
})
const detailData = ref({})

// 图表引用
const trendChartRef = ref(null)
const relationChartRef = ref(null)

// 压力衰减趋势图配置
const trendChartOption = computed(() => {
    if (!trendData.value) {
        return {
            title: {
                text: '压力衰减趋势图',
                left: 'left'
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['设计压力', '实际压力'],
                top: 30
            },
            xAxis: {
                type: 'category',
                data: []
            },
            yAxis: {
                type: 'value',
                name: '压力 (MPa)'
            },
            series: [
                {
                    name: '设计压力',
                    type: 'line',
                    data: [],
                    smooth: true
                },
                {
                    name: '实际压力',
                    type: 'line',
                    data: [],
                    smooth: true
                }
            ]
        }
    }

    return {
        title: {
            text: '压力衰减趋势图',
            left: 'left'
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                let result = `${params[0].name}<br/>`
                params.forEach(param => {
                    result += `${param.marker} ${param.seriesName}: ${param.value} MPa<br/>`
                })
                return result
            }
        },
        legend: {
            data: ['设计压力', '实际压力'],
            top: 30
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: 80,
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: trendData.value.xAxis || []
        },
        yAxis: {
            type: 'value',
            name: '压力 (MPa)'
        },
        series: [
            {
                name: '设计压力',
                type: 'line',
                data: trendData.value.series?.[0]?.values || [],
                smooth: true,
                lineStyle: {
                    width: 3,
                    type: 'dashed'
                },
                itemStyle: {
                    color: '#5470c6'
                }
            },
            {
                name: '实际压力',
                type: 'line',
                data: trendData.value.series?.[1]?.values || [],
                smooth: true,
                lineStyle: {
                    width: 3
                },
                itemStyle: {
                    color: '#91cc75'
                }
            }
        ]
    }
})
const relationChartOption = computed(() => {
  if (!graphData.value) {
    return {
      title: {
        text: '压力监测点关系图',
        left: 'left'
      },
      tooltip: {
        trigger: 'item'
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: []
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        type: 'graph',
        layout: 'none',
        coordinateSystem: 'cartesian2d',
        data: [],
        links: []
      }]
    }
  }

  // 生成X轴标签（类似图片中的周一至周日）
  const xAxisData = graphData.value.nodes?.map((node, index) => {
    const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    return days[index % days.length] + `_${node.code}`
  }) || []

  // 生成节点数据（包含坐标信息）
  const nodes = graphData.value.nodes?.map((node, index) => ({
    id: node.code,
    name: node.name,
    value: node.avgMpa,
    x: index, // X轴位置（索引）
    y: node.avgMpa, // Y轴位置（压力值）
    symbolSize: 20,
    itemStyle: {
      color: node.isAbnormal ? '#ff4d4f' : '#5470c6'
    },
    label: {
      show: true,
      formatter: function(params) {
        return `${params.data.name}\n${params.data.value}MPa`
      }
    }
  })) || []

  // 生成连接线
  const links = graphData.value.edges?.map(edge => {
    return {
      source: edge.fromCode,
      target: edge.toCode,
      value: edge.deltaMpa,
      lineStyle: {
        color: edge.isAbnormal ? '#ff4d4f' : '#2f4554',
        width: 2
      },
      label: {
        show: true,
        formatter: `Δ: ${edge.deltaMpa?.toFixed(3)}MPa`,
        backgroundColor: 'rgba(255,255,255,0.8)',
        borderColor: '#ccc',
        borderWidth: 1,
        borderRadius: 2,
      }
    }
  }) || []

  return {
    title: {
      text: '压力监测点关系图',
      left: 'left'
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        if (params.dataType === 'node') {
          return `
            <div style="padding: 5px;">
              <div style="font-weight: bold;">${params.data.name}</div>
              <div>压力: ${params.data.value} MPa</div>
              <div>状态: ${params.data.itemStyle.color === '#ff4d4f' ? '异常' : '正常'}</div>
            </div>
          `
        } else {
          const edge = graphData.value.edges?.find(e => 
            e.fromCode === params.data.source && e.toCode === params.data.target
          )
          return `
            <div style="padding: 5px;">
              <div style="font-weight: bold;">${edge?.segmentName || '压降段'}</div>
              <div>上游: ${edge?.upstreamCode}</div>
              <div>下游: ${edge?.downstreamCode}</div>
              <div>实际压降: ${edge?.actDropMpa} MPa</div>
              <div>理论压降: ${edge?.theoryDropMpa} MPa</div>
              <div>偏差: ${edge?.deltaMpa} MPa</div>
              <div>状态: ${edge?.isAbnormal ? '异常' : '正常'}</div>
            </div>
          `
        }
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData,
      axisLabel: {
        interval: 0,
        rotate: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '压力 (MPa)',
      min: function(value) {
        return Math.max(0, value.min - 0.1)
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: 80,
      containLabel: true
    },
    series: [{
      type: 'graph',
      layout: 'none',
      coordinateSystem: 'cartesian2d',
      symbolSize: 40,
      label: {
        show: true,
        position: 'top',
        formatter: '{b}\n{c}MPa'
      },
      edgeSymbol: ['circle', 'arrow'],
      edgeSymbolSize: [4, 10],
      data: nodes,
      links: links,
      lineStyle: {
        color: '#2f4554',
        curveness: 0.2
      },
      emphasis: {
        focus: 'adjacency',
        lineStyle: {
          width: 3
        }
      }
    }]
  }
})


// 获取偏差样式类
function getDeltaClass(delta) {
    if (delta === undefined || delta === null) return ''
    if (Math.abs(delta) > 0.1) return 'text-danger'
    if (Math.abs(delta) > 0.05) return 'text-warning'
    return 'text-success'
}

// 查询处理
async function handleSearch() {
    try {
        tableLoading.value = true

        // 获取压力关系图数据
        const graphRes = await getPressureGraph(searchForm)
        graphData.value = graphRes.data

        // 获取压降表格数据
        const tableRes = await getPressureTable({
            ...searchForm,
            pageNum: tableParams.pageNum,
            pageSize: tableParams.pageSize
        })
        pressureTableData.value = tableRes.data || []
        tableTotal.value = tableRes.total || 0

        // 获取压力衰减趋势数据
        const trendRes = await getAttenuationTrend(searchForm)
        trendData.value = trendRes.data

        ElMessage.success('数据加载成功')
    } catch (error) {
        console.error('获取数据失败:', error)
        ElMessage.error('获取数据失败')
    } finally {
        tableLoading.value = false
    }
}

// 重置搜索
function resetSearch() {
    searchForm.timeDimension = 1
    searchForm.time = new Date().toISOString().split('T')[0]
    searchForm.areaId = ''
    searchForm.plantId = ''
    searchForm.segmentIds = []
    searchForm.onlyAbnormal = false
    tableParams.pageNum = 1
}

// 导出数据
function handleExport() {
    proxy.download("/dispatch/system/dispatchPressureDrop/export", {
        ...searchForm,
    }, `user_${new Date().getTime()}.xlsx`);
}

// 刷新异常提示
async function refreshAbnormalTips() {
    try {
        const res = await getAbnormalTips()
        abnormalTips.value = res.data || []
        ElMessage.success('异常提示已刷新')
    } catch (error) {
        console.error('获取异常提示失败:', error)
        ElMessage.error('获取异常提示失败')
    }
}

// 查看段详情
function viewSegmentDetail(row) {
    detailData.value = row
    detailDialog.visible = true
}

// 表格分页处理
function handleSizeChange(size) {
    tableParams.pageSize = size
    handleSearch()
}

function handleCurrentChange(page) {
    tableParams.pageNum = page
    handleSearch()
}

// 图表全屏切换
function toggleFullscreen(chartType) {
    const chartRef = chartType === 'trendChart' ? trendChartRef : relationChartRef
    if (chartRef.value) {
        // 这里需要根据您的ECharts组件实现全屏功能
        ElMessage.info('全屏功能待实现')
    }
}

// 导出表格
function exportTable() {
    ElMessage.info('表格导出功能待实现')
}

// 初始化数据
async function initData() {
    try {
        // 获取段列表
        const segmentRes = await getSegmentList()
        segmentList.value = segmentRes.data || []

        // 获取异常提示
        await refreshAbnormalTips()

        // 设置默认时间
        searchForm.time = new Date().toISOString().split('T')[0]

        // 初始查询
        await handleSearch()
    } catch (error) {
        console.error('初始化数据失败:', error)
        ElMessage.error('初始化数据失败')
    }
}

onMounted(() => {
    initData()
})
</script>

<style scoped>
.app-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 15px;
}

.abnormal-tips-card {
    margin-bottom: 20px;
}

.tips-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.tips-content {
    max-height: 300px;
    overflow-y: auto;
}

.tip-item {
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
}

.tip-item:last-child {
    border-bottom: none;
}

.tip-title {
    font-weight: bold;
    margin-bottom: 5px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.tip-detail {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    margin-bottom: 5px;
    font-size: 13px;
    color: #666;
}

.tip-message {
    font-size: 14px;
    color: #e6a23c;
}

.chart-area {
    margin-bottom: 20px;
}

.chart-card {
    height: 100%;
}

.chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.table-card {
    margin-bottom: 20px;
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.mt-2 {
    margin-top: 20px;
}

.text-danger {
    color: #ff4d4f;
}

.text-warning {
    color: #faad14;
}

.text-success {
    color: #52c41a;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .search-form {
        flex-direction: column;
        align-items: stretch;
    }

    .search-form .el-form-item {
        width: 100%;
        margin-right: 0;
    }

    .chart-area .el-col {
        margin-bottom: 20px;
    }
}
</style>